package com.szyjjk.controller;

import it.geosolutions.jaiext.JAIExt;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.io.GridCoverage2DReader;
import org.geotools.coverage.grid.io.GridFormatFinder;
import org.geotools.map.GridCoverageLayer;
import org.geotools.map.MapContent;
import org.geotools.renderer.lite.StreamingRenderer;
import org.geotools.styling.SLD;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;

import ucar.ma2.ArrayFloat;
import ucar.nc2.NetcdfFileWriter;
import ucar.nc2.Dimension;
import ucar.nc2.Variable;
public class Test {
   /* public static void main(String[] args) {
        // 初始化 JAIExt
        JAIExt.initJAIEXT();

        try {
            // 读取 TIFF 文件
            File tiffFile = new File("D:\\nc文件转tif\\data\\ALG\\ALG_000.tif");
            GridCoverage2DReader reader = GridFormatFinder.findFormat(tiffFile).getReader(tiffFile);
            GridCoverage2D coverage = reader.read(null);

            // 获取 TIFF 数据
            int width = coverage.getRenderedImage().getWidth();
            int height = coverage.getRenderedImage().getHeight();
            float[][] data = new float[height][width];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    data[y][x] = coverage.getRenderedImage().getData().getSampleFloat(x, y, 0);
                }
            }

            // 创建 NetCDF 文件
            NetcdfFileWriter writer = NetcdfFileWriter.createNew(NetcdfFileWriter.Version.netcdf4, "output.nc");

            // 定义维度
            ucar.nc2.Dimension xDim = writer.addDimension("x", width);
            ucar.nc2.Dimension yDim = writer.addDimension("y", height);

            // 定义变量
            Variable var = writer.addVariable("data", DataType.FLOAT, Arrays.asList(new Dimension[]{yDim, xDim}));
            System.setProperty("ucar.nc2.jni.netcdf", "false");
            // 创建 NetCDF 文件
            writer.create();

            // 写入数据
            Array dataArray = Array.factory(DataType.FLOAT, new int[]{height, width});
            Index index = dataArray.getIndex();
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    index.set(y, x);
                    dataArray.setFloat(index, data[y][x]);
                }
            }
            writer.write(var, dataArray);

            // 关闭文件
            writer.close();

            System.out.println("TIFF 文件已成功转换为 NetCDF 文件。");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidRangeException e) {
            throw new RuntimeException(e);
        }
    }*/

    /*public static void main(String[] args) {
        // 禁用 NetCDF C 库，使用纯 Java 模式
        System.setProperty("ucar.nc2.jni.netcdf", "false");

        // 初始化 JAIExt
        JAIExt.initJAIEXT();

        try {
            // 读取 TIFF 文件
            File tiffFile = new File("D:\\nc文件转tif\\data\\ALG\\ALG_000.tif");
            GridCoverage2DReader reader = GridFormatFinder.findFormat(tiffFile).getReader(tiffFile);
            GridCoverage2D coverage = reader.read(null);

            // 获取 TIFF 数据
            int width = coverage.getRenderedImage().getWidth();
            int height = coverage.getRenderedImage().getHeight();
            float[][] data = new float[height][width];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    data[y][x] = coverage.getRenderedImage().getData().getSampleFloat(x, y, 0);
                }
            }

            // 创建 NetCDF 文件
            NetcdfFileWriter writer = NetcdfFileWriter.createNew(NetcdfFileWriter.Version.netcdf4, "D:\\output.nc");

            // 定义维度
            //ucar.nc2.Dimension xDim = writer.addDimension("x", width);
            //ucar.nc2.Dimension yDim = writer.addDimension("y", height);

            // 定义变量
            //Variable var = writer.addVariable("data", DataType.FLOAT, Arrays.asList(new Dimension[]{yDim, xDim}));

            // 创建 NetCDF 文件
            writer.create();

            // 写入数据
            Array dataArray = Array.factory(DataType.FLOAT, new int[]{height, width});
            Index index = dataArray.getIndex();
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    index.set(y, x);
                    dataArray.setFloat(index, data[y][x]);
                }
            }
           // writer.write(var, dataArray);

            // 关闭文件
            writer.close();

            System.out.println("TIFF 文件已成功转换为 NetCDF 文件。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
    public static float[][] readTiffData(String tiffPath) {
        gdal.AllRegister();
        Dataset dataset = gdal.Open(tiffPath);
        int width = dataset.getRasterXSize();
        int height = dataset.getRasterYSize();
        float[] buffer = new float[width * height];
        dataset.GetRasterBand(1).ReadRaster(0, 0, width, height, buffer);
        // 转换为二维数组
        float[][] data = new float[height][width];
        for (int i = 0; i < height; i++) {
            System.arraycopy(buffer, i * width, data[i], 0, width);
        }
        dataset.delete();
        return data;
    }

    public static void createNcFile(String ncPath, float[][] tiffData) {
        try (NetcdfFileWriter writer = NetcdfFileWriter.createNew(NetcdfFileWriter.Version.netcdf3, ncPath)) {
            // 定义维度
            Dimension latDim = writer.addDimension(null, "lat", tiffData.length);
            Dimension lonDim = writer.addDimension(null, "lon", tiffData.length);

            // 定义变量
            Variable dataVar = writer.addVariable(null, "elevation", ucar.ma2.DataType.FLOAT, "lat lon");
            //dataVar.addAttribute("units", "meters");

            // 创建文件
            writer.create();

            // 写入数据
            ArrayFloat.D2 array = new ArrayFloat.D2(latDim.getLength(), lonDim.getLength());
            for (int i = 0; i < tiffData.length; i++) {
                for (int j = 0; j < tiffData.length; j++) {
                    array.set(i, j, tiffData[i][j]);
                }
            }
            writer.write(dataVar, array);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        String tiffPath = "D:\\nc文件转tif\\data\\ALG\\ALG_000.tif";
        String ncPath = "D:\\output.nc";

        // 读取TIFF数据
        float[][] tiffData = readTiffData(tiffPath);

        // 生成NetCDF文件
        createNcFile(ncPath, tiffData);
    }
}
